package com.nulldev.util.web.HttpServer3.extensions.envStats;

import java.util.List;

import com.nulldev.util.io.IOUtils;
import com.nulldev.util.io.util.BufferManager;
import com.nulldev.util.io.util.BufferManager.Buffer;
import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.manage.nullUtil;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;

public class IOBuffersStatsPage extends HttpPage3 {

	private static final String JSON_MIME = "application/json; charset=utf-8";

	public IOBuffersStatsPage() {
		super("/debug/buffers");
	}

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		if (!nullUtil.IS_NON_MAINLINE_BUILD)
			return new Response(204, BLANK_IO_STREAM);
		final UniJsonValue uv = UniJsonValue.object(5);
		final BufferManager bufMan = IOUtils.getBufferManager();
		uv.add("directAllocation", bufMan.allowsDirectAllocation());
		uv.add("mmapAllocation", bufMan.allowsMMAPAllocation());
		uv.add("deallocatorPresent", bufMan.supportsDeallocation());
		uv.add("totalBufferCount", bufMan.buffers());
		final List<Buffer> buffs = bufMan.bufferList();
		final UniJsonValue buffers = UniJsonValue.array(buffs.size());
		buffs.forEach((buffer) -> {
			buffers.add(String.valueOf(buffer));
		});
		uv.add("buffers", buffers);
		return new Response(200, uv, uv).setCustomMime(JSON_MIME);
	}

}
